package org.redmagic.service.ui;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.UUID;

import org.redmagic.service.domain.ui.DisplayProperty;
import org.springframework.stereotype.Service;

import com.google.common.collect.HashBasedTable;
import com.google.common.collect.Table;

@Service
public class HashBasedTableService implements RedMagicService {

	private Table<String, List<String>, DisplayProperty> displayProperties;
	private Map<String, DisplayProperty> idToProperty;
	
	public HashBasedTableService() {
		this.displayProperties = HashBasedTable.create();
		this.idToProperty = new HashMap<String, DisplayProperty>();
	}
	
	@Override
	public void create(DisplayProperty property) {
		property.setId(UUID.randomUUID().toString());
		System.out.println("Creating property with id: " + property.getId());
		this.displayProperties.put(property.getName(), property.getTagNames(), property);
		this.idToProperty.put(property.getId(), property);
	}

	@Override
	public void update(DisplayProperty property) {
		System.out.println("Updating property with id: " + property.getId());
		// go get the old property
		DisplayProperty oldProperty = getPropertyById(property.getId());
		this.displayProperties.remove(oldProperty.getName(), oldProperty.getTagNames());
		this.displayProperties.put(property.getName(), property.getTagNames(), property);
		this.idToProperty.put(property.getId(), property);
	}

	@Override
	public List<DisplayProperty> viewAllProperties() {
		TreeSet<String> keys = new TreeSet<String>(this.displayProperties.rowKeySet());
		List<DisplayProperty> props = new ArrayList<DisplayProperty>();
		Iterator<String> iter = keys.iterator();
		while (iter.hasNext()) {
			String rowName = iter.next();
			Map<List<String>, DisplayProperty> row = this.displayProperties.row(rowName);
			Set<List<String>> columns = row.keySet();
			Iterator<List<String>> columnIter = columns.iterator();
			while (columnIter.hasNext()) {
				List<String> columnName = columnIter.next();
				props.add(this.displayProperties.get(rowName, columnName));
			}
		}
		return props;
	}

	@Override
	public DisplayProperty getPropertyById(String id) {
		return this.idToProperty.get(id);
	}
}
